package com.kuang.thread.syn;

public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account("结婚基金",10000);

        Drawing you = new Drawing(account, 5000, "YOU");
        Drawing she = new Drawing(account, 6000, "SHE");
        you.start();
        she.start();

    }
}

class Account {
    String name;
    int money;

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}

class Drawing extends Thread {
    //账户
    private Account account;
    //取了多少钱
    private int drawingMoney;
    //现在手里有多少钱
    private int nowMoney;

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);//extends Thread
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    //取钱
    @Override
    public void run() {
        //锁的对象就是可能会发生冲突的变量
        synchronized (account){
            //判断是否有钱
            if (account.money - drawingMoney < 0) {
                System.out.println(this.getName() + "余额不足");
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            nowMoney=account.money - drawingMoney;
            account.money=nowMoney;
            System.out.println(this.getName() + "成功取钱"+drawingMoney+"账户剩余"+nowMoney);
        }
    }
}